#include "astar_lnklist.h"
/**
** @brief get the case with position x and y in the matrix from the list
**
** @param l the list containing the case with position x and y
** @param x position x
** @param y position y
**
** @return the case with position x and t
*/
s_case *get_case(s_case *l, int x, int y)
{
    while (l && !(l->x == x && l->y == y))
        l = l->next;

    return (l);
}

/**
** @brief get the case with the minimum cost from the list
**
** @param l list of cases
**
** @return the case with the minimum cost
*/
s_case *get_min(s_case *l)
{
    s_case *min;
    s_case *new;

    min = l;
    if (!l)
        return (NULL);

    while (l)
    {
        if (l->total < min->total)
            min = l;
        l = l->next;
    }

    new = malloc(sizeof (s_case));
    new->x = min->x;;
    new->y = min->y;
    new->manh = min->manh;
    new->distt = min->distt;
    new->total = min->total;
    new->prev = min->prev;
    new->next = NULL;

    return (new);
}

/**
** @brief check if the case with position x and y exist in l
**
** @param l list of cases
** @param x position x
** @param y position y
**
** @return return 1 if the case exist in l, 0 if not
*/
int   is_exist(s_case *l, int x, int y)
{
    while (l && !(l->x == x && l->y == y))
        l = l->next;

    if (!l)
         return (0);
     return (1);
}

/**
** @brief add the case n in list l
**
** @param l list of cases
** @param n the element to add
*/
void  add_list(s_case **l, s_case *n)
{
    s_case *curr = *l;

    while (curr && curr->next)
        curr = curr->next;

    if (!curr)
        *l = n;
    else
        (curr)->next = n;
}

void  edit_list(s_case *c, int total, s_case *prev)
{
    c->total = total;
    c->prev = prev;
}

/**
** @brief remove the element with position x and y in the list
**
** @param l list of cases
** @param x position x
** @param y position y
*/
void  remove_list(s_case **l, int x, int y)
{
    s_case *old = NULL;
    s_case *curr = *l;

    while (curr && curr->next && !(curr->x == x && curr->y == y))
    {
        old = curr;
        curr = curr->next;
    }

    if (curr == NULL)
        return;

    if (curr->x != x || curr->y != y)
        return;

    if (old == NULL)
        *l = (*l)->next;
    else
        old->next = curr->next;

    free(curr);
}
